package com.gmall.web.controller;

import com.gmall.common.result.Result;
import com.gmall.web.service.ClazzService;
import com.gmall.web.utils.FreemarkerUtil;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("testftl")
public class TestFTLController {

    @GetMapping("test1")
    public Result<String> test1(){
        return Result.ok("hello");
    }

    @Autowired
    ClazzService clazzService;

    @GetMapping("genTestHTML/{htmlFileName}")
    public String genTestHTML(@PathVariable String htmlFileName) throws IOException, TemplateException {

        Map map_data=new HashMap();
        map_data.put("name", "张三 ");
        map_data.put("message", "欢迎来到神奇的电商世界！");
        map_data.put("success",false);
        map_data.put("today", new Date());
        //模拟从数据库查询
        map_data.put("clazzList",clazzService.getClazzList());
        map_data.put("point", 102920122);
        map_data.put("aaa", true);

        FreemarkerUtil freemarkerUtil=new FreemarkerUtil();
        //获取部署文件的resource目录
        String classpath = this.getClass().getResource("/").getPath();

        freemarkerUtil.createHtml(map_data,"test",
                classpath + "/static/" + htmlFileName +".html");
//        //1.创建配置类
//        Configuration configuration=new Configuration(Configuration.VERSION_2_3_30);
//        //2.设置模板所在的目录
//        configuration.setDirectoryForTemplateLoading(
//                new File("D:\\01_2203A\\gmall\\gmall-parent\\web\\src\\main\\resources\\template\\"));
//        //3.设置字符集
//        configuration.setDefaultEncoding("utf-8");
//        //4.加载模板
//        Template template = configuration.getTemplate("test.ftl");
//
//        //5.创建数据模型
//        Map map_data=new HashMap();
//        map_data.put("name", "张三 ");
//        map_data.put("message", "欢迎来到神奇的电商世界！");
//        //6.创建Writer对象
//        Writer out_html =new FileWriter(new File("d:\\test.html"));
//        //7.输出
//        template.process(map_data, out_html);//template + map = html
//        //8.关闭Writer对象
//        out_html.close();

        return "OK";
    }
}
